package com.example.dingtalklogin.service.executor;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.dingtalklogin.common.exception.CheckException;
import com.example.dingtalklogin.dao.User;
import com.example.dingtalklogin.dao.UserRepository;
import com.example.dingtalklogin.service.dto.DingtalkLoginCmd;
import com.example.dingtalklogin.service.dto.data.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DingtalkLoginCmdExe {

    private UserRepository userRepository;

    @Autowired
    public DingtalkLoginCmdExe(UserRepository userRepository){
        this.userRepository = userRepository;
    }

    public UserDto execute(DingtalkLoginCmd cmd){
        cmd.validate();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getDingtalkUnionId, cmd.getUnionId());
        User user = userRepository.getOne(queryWrapper);
        if(user == null){
            throw new CheckException("钉钉登录未找到绑定用户，请先绑定用户");
        }
        UserDto userDto = new UserDto();
        userDto.setUsername(user.getUsername());
        userDto.setId(user.getId());
        userDto.setBindingDingtalk(true);
        return userDto;
    }
}
